package com.springbootblog.service.serviceImpl.fontend;

import com.springbootblog.controller.fontend.IndexController;
import com.springbootblog.dao.MessageDao;
import com.springbootblog.pojo.Message;
import com.springbootblog.pojo.User;
import com.springbootblog.service.fontend.MessageService;
import com.springbootblog.utils.Email;
import com.springbootblog.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MessageServiceImpl implements MessageService
{
    /**
     * 定义一个静态常量日志对象
     */
    private static final Logger logger = LoggerFactory.getLogger(IndexController.class);

    /**
     * 自动装载（dao接口注入）
     */
    @Autowired
    private MessageDao messageDao;

    /**
     * 获取留言列表
     * @return
     */
    @Override
    public Map<String,Object> getMessageList()
    {
        Integer messageCount = 0;
        // 查留言列表
        List<Message> messageList = messageDao.getMessageList();
        for (int i = 0; i < messageList.size(); i++)
        {
            if(messageList.get(i).getFigureurl_qq() != "" && messageList.get(i).getFigureurl_qq() != null)
            {
                messageList.get(i).setFigureurl_qq(messageList.get(i).getFigureurl_qq());
            }
            else if(messageList.get(i).getFigureurl_wx() != "" && messageList.get(i).getFigureurl_wx() != null)
            {
                messageList.get(i).setFigureurl_qq(messageList.get(i).getFigureurl_wx());
            }
            messageCount++;
            // 查二级回复
            List<Message> com_two = messageDao.getMessageListTwo(messageList.get(i).getId().toString());
            if(com_two != null)
            {
                for (int j = 0; j < com_two.size(); j++)
                {
                    if(com_two.get(j).getFigureurl_qq() != "" && com_two.get(j).getFigureurl_qq() != null)
                    {
                        com_two.get(j).setFigureurl_qq(com_two.get(j).getFigureurl_qq());
                    }
                    else if(com_two.get(j).getFigureurl_wx() != "" && com_two.get(j).getFigureurl_wx() != null)
                    {
                        com_two.get(j).setFigureurl_qq(com_two.get(j).getFigureurl_wx());
                    }
                    messageCount++;

                    Message message = messageDao.getMessageListTwoReply(com_two.get(j).getReplyid().toString());
                    com_two.get(j).setReply_nickname(message.getNickname());
                    if(message.getFigureurl_qq() != "" && message.getFigureurl_qq() != null)
                    {
                        com_two.get(j).setReply_figureurl_qq(message.getFigureurl_qq());
                    }
                    else if(message.getFigureurl_wx() != "" && message.getFigureurl_wx() != null)
                    {
                        com_two.get(j).setReply_figureurl_qq(message.getFigureurl_wx());
                    }
                }
            }
            messageList.get(i).setCom_two(com_two);
        }
        Map<String,Object> result = new HashMap<>(3);
        result.put("messageCount",messageCount);
        result.put("messageList",messageList);
        result.put("code",1);
        return result;
    }

    /**
     * 注入邮箱类
     */
    @Autowired
    private Email emailObj;

    /**
     * 提交留言
     * @param email
     * @param content_reply
     * @param replyid
     * @return
     */
    @Override
    public Map<String, Object> putmessage(String email, String content_reply, String replyid, HttpServletRequest request)
    {
        /*// 获取登录用户session信息
        HttpSession session = request.getSession();
        // 获取id
        Integer id = (Integer) session.getAttribute("id");//*/
        // 获取token
        String token = request.getHeader(JwtUtils.token_name);
        // 解析token
        Claims paramList = JwtUtils.parseJWT(token);
        Integer id;
        if(paramList == null || paramList.equals(null))
        {
            id = null;
        }
        else
        {
            id = (Integer) paramList.get("id");
        }
        //Integer id = (Integer) paramList.get("id");
        if(id == null)
        {
            Map<String,Object> result = new HashMap<>(2);
            result.put("code",-1);
            result.put("msg","您没有登录！");
            return result;
        }
        // 获取email
        //String sessionEmail = (String) session.getAttribute("email");
        String sessionEmail = (String) paramList.get("email");
        // 如果邮箱字段有值，说明当前用户没有绑定邮箱，将邮箱写入数据库
        if(!email.isEmpty())
        {
            messageDao.updateUserInfo(id.toString(), email);
        }
        else if(!sessionEmail.isEmpty())
        {
            email = sessionEmail;
        }
        else
        {
            Map<String,Object> result = new HashMap<>(2);
            result.put("code",-2);
            result.put("msg","请填写您的邮箱！");
            return result;
        }
        // System.out.println("replyid:"+replyid);
        if(replyid == null || replyid.isEmpty())
        {
            replyid = "0";
        }
        // System.out.println("replyid:"+replyid);
        // 判断回复那条留言的id
        String returnid = "0";
        Integer reply_user_id = 0;
        if(!replyid.equals(0) && !replyid.equals("0"))
        {
            // System.out.println("replyid进来了");
            Message message = messageDao.getMessageInfo(replyid);
            // System.out.println(message.toString());
            returnid = message.getReturnid().toString();
            if(returnid.equals("0"))
            {
                returnid = replyid;
            }
            else
            {
                returnid = message.getReturnid().toString();
            }
            reply_user_id = message.getUid();
        }
        // ================================================================
        // 发邮件
        String mailto = "";
        String subject = "";
        String body = "";
        if(reply_user_id != id )
        {
            // reply_user_id 为 0 时是评论，否则为回复
            if(reply_user_id == 0)
            {
                if(id != 1)
                {
                    mailto = "805795955@qq.com";
                    subject = "时间里的博客留言";
                    body = "您的博客收到留言，内容为“" + content_reply + "”，请及时查看。"; //邮件内容
                }
            }
            else
            {
                User user = messageDao.getUserInfoById(reply_user_id.toString());
                mailto = user.getEmail();
                if(mailto != null && !mailto.isEmpty())
                {
                    subject = "时间里的博客留言回复"; //邮件主题
                    body = "您的博客收到留言，内容为“" + content_reply + "”，请及时查看。"; //邮件内容
                }
            }
            // 发邮件
            emailObj.sendSimpleMail(mailto,subject,body);
        }

        // 写入数据库
        Message  message = new Message();
        message.setUid(id);
        message.setReplyid(Integer.parseInt(replyid));
        message.setContent(content_reply);
        message.setReturnid(Integer.parseInt(returnid));
        Integer res = messageDao.addMessageData(message);

        Map<String,Object> result = new HashMap<>(2);
        result.put("code",1);
        result.put("msg","操作成功！");
        return result;//*/
    }
}
